package org.example.predicates;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义注解的实现
 *
 * 在配置自定义断言的时候，必须使用
 *       routes[1]:
 *         id: cloud_baidu
 *         uri: https://www.baidu.com/
 *         predicates[0]:
 *           MyHeader=token,1234
 * 注意自定义的类型名称一定要是 RoutePredicateFactory结尾的
 * 用前面的名进行配置
 * @author control
 */
@Component
public class MyHeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<MyConfig> {
    public MyHeaderRoutePredicateFactory() {
        super(MyConfig.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyConfig config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String value = serverWebExchange.getRequest().getHeaders().getFirst(config.getKey());
                System.out.println("你在请求头中传入的值"+value);
                if (config.getValue().equals(value)) {
                    System.out.println("被自定义断言放行，通过，value为"+value);
                    return true;
                }
                System.out.println("被自定义断言拦截，不能通过，value为"+value);
                return false;
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {

        // - MyHeader=bbb，ccc
        //-MyHeader=bbb，cccc
        //[bbb cccc]
        //bbb赋值给MyConfig#key
        // cccc赋值给MyConfig#value


        return Arrays.asList("key","value");
    }
}
